package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.evaluate.bean.ShareBean;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.OldReadRecordBean;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MyWorkFileManager;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.modules.scan.bean.EpaperQRInfo;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.ShareDialog;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.common.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yyf on 2017/4/17.
 */

public class LearnRecordH5Activity extends BaseHtmlActicity {

    private static final String TAG = "LearnRecordH5Activity";

    private int visitCount=0;

    private WorkContents workContents = new WorkContents();
    private String workId;


    public void onEventMainThread(SubmitEvent submitEvent) {
        Log.d(TAG, "onEventMainThread+" + submitEvent.getId() + "--Json:" + submitEvent.getJson());

        if (submitEvent.getId().equals("JumpToOldListen_Speak")) { //H5通知：加载老的听说模考页面
//            JumpToOldListen_Speak(submitEvent);
        } else if (submitEvent.getId().equals("JumpToOldRead")) {//跳转到跟读。
            JumpToOldRead(submitEvent);
        } else if (submitEvent.getId().equals("GetComments")) {//标题栏显示评论按钮
//            showCommentsBtn(submitEvent);
        } else if (submitEvent.getId().equals("GetShareInfo")) { //标题栏显示分享按钮
            Log.d(TAG, "获取到的json" + submitEvent.getJson());
            visitCount++;
            Log.d(TAG, "######visitCount#########" + visitCount);
            showShareBtn(submitEvent);
        } else if (submitEvent.getId().equals("GetDubbingInfo")) {
            String arg = submitEvent.getJson();
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(arg);
                if (jsonObject.has("title")) {
                    /*wx_text = jsonObject.getString("title");*/
                    wx_text = "配音内容《" + jsonObject.getString("title") + "》";
                }
            } catch (JSONException e) {
                e.printStackTrace();


            }
        } else if (submitEvent.getId().equals("SetTitle")) {
            try {
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                if (jsonObject.has("title")) {
                    String currentTitle = jsonObject.getString("title");
                    String tag = "";
                    if (doWorkType == 1) {
                        tag = "订正错题  ";
                    }
                    setTitleText(tag + currentTitle);

                    if (currentTitle.equals("学习记录")) {
                        hideRightImgBtn();
                    }

                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        } else if (submitEvent.getId().equals("GetWeiXinAppId")) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("appId", EConstants.WEIXIN_APP_ID);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            sendCallBack(submitEvent.getCallbackId(), jsonObject.toString());
        } else if (submitEvent.getId().equals("onRevised")) {
            String arg = submitEvent.getJson();
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(arg);
            Integer index = jsonObject.getInteger("index");
            workContents.setcId(jsonObject.getString("cId"));
            workContents.setPackageId(jsonObject.getString("packageId"));
            workContents.setModuleId(jsonObject.getInteger("moduleId"));
            workContents.setVersionId(jsonObject.getString("versionId"));
            workContents.setResourceName(jsonObject.getString("resourceName"));
            workContents.setResourceType(jsonObject.getString("resourceType"));
            workContents.setContentId(jsonObject.getInteger("contentId"));
            workContents.setDoWorkId(jsonObject.getString("doWorkId"));
            workContents.setExamMode(0);
            workContents.setCheckedResource(String.valueOf(index));
            workContents.setParentVersionId(jsonObject.getString("parentVersionId"));
            workContents.setWorkScore(jsonObject.getFloat("workScore"));
            workId = jsonObject.getString("workId");
            showDownloadProgress("玩命加载中,请耐心等待......");
            jumpToDoWorkAfterDownload(workContents);
        }
    }

    private void showShareBtn(final SubmitEvent submitEvent){
        showRightBtn();
        setImgRightBtn(R.mipmap.ic_share);
        setImgRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                if(EConstants.IS_YOUKE){
                    NewLoginDialog newLoginDialog=new NewLoginDialog(LearnRecordH5Activity.this);
                    newLoginDialog.showLoginDialog();

                }else {
                    Gson gson = new Gson();
                    Log.d(TAG, "获取到的json" + submitEvent.getJson());
                    ShareBean shareBean = gson.fromJson(submitEvent.getJson(), ShareBean.class);
                    ShareDialog shareDialog = new ShareDialog(LearnRecordH5Activity.this, shareBean);
                    shareDialog.setParamForAddPoint(shareBean.getDoWorkId(), AddPointTypes.SHERE_SCORE);
                    shareDialog.show();
                }
            }
        });
    }

    private void JumpToOldRead(SubmitEvent submitEvent) {
        Gson gson = new Gson();
        OldReadRecordBean oldReadRecordBean = gson.fromJson(submitEvent.getJson(), OldReadRecordBean.class);
        OldReadRecordBean.Params params = oldReadRecordBean.params;
        Answer answer = new Answer();
        answer.setComment(params.comment);
        answer.setResourceName(params.resourceName);
        answer.setResourceType(params.resourceType);
        answer.setVersionId(params.versionId);
        answer.setParentVersionId(params.parentVersionId);
        answer.setModuleId(params.moduleId);
        answer.setcId(params.cId);
        answer.setDoWorkPackageUrl(params.doWorkPackageUrl);

        getSynReadUrl(answer);
    }

    private void getSynReadUrl(final Answer answer) {
        String pUrl = "";
        pUrl = answer.getDoWorkPackageUrl();
        if (TextUtils.isEmpty(pUrl)) {
            pUrl = answer.getDoWorkLocalPath();
        }
        String name = pUrl.substring(pUrl.lastIndexOf("/") + 1,
                pUrl.lastIndexOf("."));
        Type type = new TypeToken<List<WorkAnswers<RepeatAnswerInfo>>>() {
        }.getType();
        String path = ESystem.getAnswersUserAnswerPath(name);
        final ArrayList<String> audioPaths = new ArrayList<String>();
        final String prePath = EConstants.FILE_PREFIX
                + ESystem.getAnswersUuidPath(name) + File.separator;
        EpaperDao.getInstance().getSerializableObjects(path, type,
                new BaseExtCallBack(LearnRecordH5Activity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(final Object data) {
                        List<WorkAnswers<RepeatAnswerInfo>> b = (List<WorkAnswers<RepeatAnswerInfo>>) data;
                        for (int i = 0; i < b.size(); i++) {
                            WorkAnswers<RepeatAnswerInfo> workAnswers = b
                                    .get(i);
                            List<RepeatAnswerInfo> aInfos = workAnswers
                                    .getAnswers();
                            for (int j = 0; j < aInfos.size(); j++) {
                                RepeatAnswerInfo repeatAnswerInfo = aInfos
                                        .get(j);
                                audioPaths.add(prePath
                                        + repeatAnswerInfo.getAudioUrl());
                            }
                        }

                        Module module = new Module();

                        ModuleInfo moduleInfo = new ModuleInfo();
                        moduleInfo.setModuleId(answer.getModuleId());
                        moduleInfo.setcId(answer.getcId());
                        module.setModuleInfo(moduleInfo);
                        ModuleContent c = new ModuleContent();
                        c.setResourceName(answer.getResourceName());
                        c.setResourceType(answer.getResourceType());
                        c.setVersionId(answer.getVersionId());
                        c.setParentVersionId(answer.getParentVersionId());
                        ArrayList<ModuleContent> mList = new ArrayList<ModuleContent>();
                        mList.add(c);
                        module.setResourceList(mList);

                        EpaperJumpManager.jumpToDictaion(answer, R.string.go_back,
                                LearnRecordH5Activity.this, module, audioPaths);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        handLocalWorkFile(answer);

                    }

                    @Override
                    public void failed(Object data)
                    {
                        super.failed(data);
                        handLocalWorkFile(answer);
                    }
                });
    }

    private String title;
    private String url;
    private int type;

    @Override
    protected void init() {
        super.init();
        setValideSource(false);
        Intent intent = getIntent();
        title = intent.getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
        url = intent.getStringExtra(IntentFlag.INTENT_FLAG_URL);
       // url="http://testm.teacher.jiaofucloud.cn/v1707_haitangban/onlinePaper/detail.html";
        type = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
        doWorkType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_DO_WORK_TYPE, 0);
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }

        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        if (verifyInfo != null) {
            String accessToken = verifyInfo.getAccessToken();
            String clientId = verifyInfo.getClientId();
            String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
            String brandId = EApplication.BRAND_ID + "";
            String startURL = EpaperConstant.URL_LEARN_RECORD_H5 + "accessToken=" + accessToken + "&clientId=" + clientId + "&userId=" + userId + "&brandId=" + brandId;
            if (!TextUtils.isEmpty(url)) {
                startURL = url;
            }
            if (("我的作品").equals(title)){
                startURL +="&workType=dub";
                setTitleText( title);
            }
            setStartURL(startURL);
        } else {
            showToastError("无法获取用户信息，请重新登录后重试");
            finish();
        }
        webView.getSettings().setJavaScriptEnabled(true);
//        setTitleText( title);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                finish();
            }
        });
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        try {
            final DownLoadInfo downLoadInfo = item.getInfo();
            if (downLoadInfo != null) {
                if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FILE_DOWNLOAD) {
                    hideDownloadHorizontalProgressBar();
                    hideCancelButtonOfDownloadProgress();
                }  else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED
                        || downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP
                        || downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                    ToastUtil.INSTANCE.toastCenterError(R.string.download_fail);
                    hideDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_COMPLETED) {
                    //线上作答要去检查html离线包，所以下载完成先不隐藏下载框
                        if (LearnRecordH5Activity.this.isTopActivity()) {
                            judgeDownloadInfoAndWorkContents(downLoadInfo,workContents);
                        } else {
                            hideDownloadProgress();
                        }
                    }
                 else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_DOWNLOADING) {
                    HomeWorkUtil.matchCurrentDownloadingHomework(downLoadInfo, workContents, new HomeWorkUtil.ResoureTypeMatchListener() {
                        @Override
                        public void homeworkMatchSuccess(DownLoadInfo downLoadInfo) {
                            Log.e(TAG, "onEventMainThread STATUS_DOWNLOADING: " + downLoadInfo.getChapterName() + "  " + downLoadInfo.getResourceName() + "  progress" + downLoadInfo.getProgress());
                            updateDownloadProgress(downLoadInfo.getProgress());
                        }

                        @Override
                        public void homeworkMatchFailed() {

                        }
                    });
                }
            } else {
                CWLog.e(TAG, "downLoadInfo == null:");
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }
    }

    private void judgeDownloadInfoAndWorkContents(DownLoadInfo downLoadInfo, final WorkContents currentWorkContents) {
        //防止取消了仍会打开
        if (isDownloadProessBarShowing()) {
            if (ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(currentWorkContents.getModuleId())) {

            } else {
                hideDownloadProgress();
            }
        }
        HomeWorkUtil.matchCurrentDownloadingHomework(downLoadInfo, currentWorkContents, new HomeWorkUtil.ResoureTypeMatchListener() {
            @Override
            public void homeworkMatchSuccess(DownLoadInfo downLoadInfo) {
                jumpToDoWorkAfterDownload(currentWorkContents);
            }

            @Override
            public void homeworkMatchFailed() {
                hideDownloadProgress();
            }
        });
    }

    /**
     * 下载完资源之后跳转作业方法
     * @param workContents 作业内容
     */
    private void jumpToDoWorkAfterDownload(WorkContents workContents) {
        try {
            DownLoadInfo downLoadInfoNew = DownLoad.getInstance().isPackageExist_New(workContents.getPackageId(), workContents.getcId(), workContents.getModuleId() + "", workContents.getVersionId());
            DownLoadInfo downLoadInfo = DownLoad.getInstance().isPackageExist(workContents.getPackageId(), workContents.getcId());
            String mainJsonPath = ESystem.getPackagesMainJsonPath(workContents.getPackageId(), workContents.getcId());
            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(workContents.getPackageId(), workContents.getcId());
            String resourcePath = ESystem.getPackagesResourcePath(workContents.getPackageId(), workContents.getcId());

            //资源不存在,而且本地也没有，就去下载了
            if (downLoadInfoNew == null && downLoadInfo == null) {
                getCatalogueInfoAction(workContents.getPackageId(),workContents.getcId(),workContents.getModuleId(), workContents.getVersionId(),workContents.getResourceName(),workContents.getResourceType());
            } else {
                if (downLoadInfoNew != null) {
                    //新资源
                    File packagesCatalogueFile_New = new File(ESystem.getPackagesCatalogueNew(workContents.getPackageId(), workContents.getcId(), workContents.getModuleId() + "",  workContents.getVersionId()));
                    File packagesCatalogueMediaFile_New = new File(ESystem.getPackagesMediaPath_New(workContents.getPackageId(), workContents.getcId(), workContents.getModuleId() + "",  workContents.getVersionId()));

                    File packagesCatalogueResourceFile_New = new File(ESystem.getPackagesResourcePath_New(workContents.getPackageId(), workContents.getcId(), workContents.getModuleId() + "",  workContents.getVersionId()));//其他作业需要验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueMediaFile_New.exists() && packagesCatalogueResourceFile_New.exists()) {
                            hideDownloadProgress();
                            EpaperJumpManager.jumpToListenSpeakWorkNew(R.string.go_back, this,true, workId, 0, downLoadInfoNew, "0", workContents.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE, 0, workContents, 0, doWorkType);
                            finish();
                        } else {
                            //防止下载的包结构有问题，这时应该取消弹框
                            hideDownloadProgress();
                    }

                } else if (downLoadInfo != null) {
                    //旧资源
                    if (new File(mainJsonPath).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists()) { //下载的所有文件都必须没有丢失，否则就去下载
                        localJumpAction(workContents, downLoadInfo,workId, false);//
                    } else {
                        //防止下载的包结构有问题，这时应该取消弹框
                        hideDownloadProgress();
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }

    /**
     * 获取Module信息后跳转至做作业
     *
     * @param workContent
     * @param downLoadInfo
     */
    private void localJumpAction(final WorkContents workContent, final DownLoadInfo downLoadInfo, final String workId, final boolean isCheckUpdateFail) {
        try {
            String path = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            EpaperDao.getInstance().getSerializableObjects(path, Main.class,

                    new BaseExtCallBack(LearnRecordH5Activity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            hideDownloadProgress();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            hideDownloadProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Main数据失败");
                            if (downLoadInfo.getStatus() != DownloadStatus.STATUS_UPZIPING) {
                                super.failed(errorCode, data);
                            }
                        }

                        @Override
                        public void success(Object data) {
                            Main main = (Main) data;
                            getCatalogueFile(workContent, downLoadInfo, main.getCatalogueFile(), main.getJsonVersion(),workId,"0",0, isCheckUpdateFail);
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }
    }

    /**
     * 获取目录内容信息
     *
     * @param workContent  目录内容信息地
     * @param downLoadInfo
     * @param path
     * @param jsonVersion
     */
    private void getCatalogueFile(final WorkContents workContent, final DownLoadInfo downLoadInfo, String path, final String jsonVersion, final String workId,final String classId,final int serviceId, final boolean isCheckUpdateFail) {
        try {
            path = ESystem.getPackagesPath(LearnRecordH5Activity.this) + File.separator + path;
            Type responseType = new TypeToken<List<Module>>() {
            }.getType();
            EpaperDao.getInstance().getSerializableObjects(path, responseType,
                    new BaseExtCallBack(LearnRecordH5Activity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            hideDownloadProgress();
                            CWLog.e(TAG, data.toString());
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            hideDownloadProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源", true);
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void success(Object data) {
                            try {
                                List<Module> modules = (List<Module>) data;
                                Module module = HomeWorkUtil.getModule(modules, workContent);
                                if (module == null) {
                                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "解压后没有找到指定module", getRemarkNoFoundModule(workContent), true);
                                }
                                int index = HomeWorkUtil.getModuleContentIndex(module, workContent);
                                EpaperJumpManager.jumpToListenSpeakWork(R.string.go_back, LearnRecordH5Activity.this,workId , downLoadInfo, module, index, classId, jsonVersion, workContent.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE, serviceId, workContent, 0, doWorkType,true);
                                finish();
                            } catch (Exception e) {
                                e.getStackTrace();
                                hideDownloadProgress();
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }
    }

    private String getRemarkNoFoundModule(WorkContents workContent) {
        return workContent.getcId() + "_" + workContent.getPackageId() + "  " + workContent.getResourceName();
    }



    /**
     * 获取章节目录信息以及下载地址
     */
    private void getCatalogueInfoAction(final String packageId,final String cId,final int moduleId,final String versionId,final String resourceName,final String resourceType) {
        try {
            EpaperDao.getInstance().getCatalogueInfoNew(packageId, cId, moduleId + "", versionId, new BaseExtCallBack(LearnRecordH5Activity.this) {

                @Override
                public void success(Object data) {
                    try {
                        EpaperQRInfo epaperQRInfo = (EpaperQRInfo) data;
                        String url = epaperQRInfo.getDownLoadUrl();

                        //测试地址  url="https://file.dzb.ciwong.com/epaper/20170912145905/catalogue_5238_6141001_v1505199545.res";
                        final DownLoadInfo downLoadInfo = new DownLoadInfo();
                        downLoadInfo.setType(epaperQRInfo.getcType());
                        downLoadInfo.setResourceName(resourceName);
                        downLoadInfo.setResourceType(resourceType);
                        downLoadInfo.setBookId(epaperQRInfo.getPackageId());
                        downLoadInfo.setBookName(epaperQRInfo.getPackageName());
                        downLoadInfo.setIconUrl(epaperQRInfo.getPackageCover());
                        downLoadInfo.setChapterId(epaperQRInfo.getcId());
                        downLoadInfo.setChapterName(epaperQRInfo.getcName());
                        //旧资源不用存moduleId 和versionId
                        downLoadInfo.setModuleId(moduleId + "");
                        downLoadInfo.setVersionId(versionId);
                        downLoadInfo.setUrl(url);

                        downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(LearnRecordH5Activity.this, url));
                        downLoadInfo.setStatus(DownloadStatus.STATUS_LOADING);
                        downLoadInfo.setHash(epaperQRInfo.getHash());
                        String fileSize = epaperQRInfo.getFileSize();
                        if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                            downLoadInfo.setSize(fileSize.split(" ")[0]);
                        }

                        if (DialogUtil.sdIsFullForDownload(LearnRecordH5Activity.this, downLoadInfo)) {
                            DialogUtil.showSdFullDialog(LearnRecordH5Activity.this, downLoadInfo.getSize());
                            return;
                        }
                        if (NetworkUtils.isWifiOnline()) {
                            DownLoad.getInstance().addTask(downLoadInfo);

                        } else {
                            hideDownloadProgress();
                            DialogUtil.showWIFIDialog(LearnRecordH5Activity.this, downLoadInfo);

                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                        hideDownloadProgress();
                    }
                }

                @Override
                public void failed(int errorCode, Object data) {
                    hideDownloadProgress();
                    String errorMsg = data == null ? "" : data.toString();
                    String logDec = "packageId:" + packageId + ",cId:" + cId + errorCode + ",errorMsg:" + errorMsg;
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                    ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");
                }

                @Override
                public void failed(Object data) {
                    hideDownloadProgress();
                    String errorMsg = data == null ? "" : data.toString();
                    String logDec = "packageId:" + packageId + "mcId:" + cId + ",errorMsg:" + errorMsg;
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                    ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");
                }
            });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }
    }


    @Override
    protected void loadData() {
        loadUrl(startURL.toString());
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
    }

    @Override
    public void finish() {
        if (webView.canGoBack()) {
            webView.goBack();
            hideRightBtn();//隐藏右边的评论按钮
            return;
        }
        super.finish();
    }


    private void handLocalWorkFile(final Answer answer) { //本地跟读作业被删除，重新下载。
        //下载资源
        DownLoadInfo downLoadInfo = answerToDownLoadInfo(answer);
        showCricleProgress(R.string.loading_work);

        MyWorkFileManager.getInstance().addWorkToDownLoad(downLoadInfo, new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
            }


            @Override
            public void failed(Object data) {
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {

                hideCricleProgress();
                //下载完重新自动打开
                getSynReadUrl(answer);
            }

        });
    }

    private DownLoadInfo answerToDownLoadInfo(Answer answer) {
        DownLoadInfo dInfo = new DownLoadInfo();
        dInfo.setBookId(answer.getPackageId());
        dInfo.setChapterId(answer.getcId());
        dInfo.setUrl(answer.getDoWorkPackageUrl());
        dInfo.setSavePath(
                FileUtil.getSavePathByUrl(LearnRecordH5Activity.this, answer.getDoWorkPackageUrl()));
        dInfo.setStatus(DownloadStatus.STATUS_LOADING);
        return dInfo;
    }


    @Override
    protected void onResume() {
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



}
